package com.etc.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CaptchaUtil {

	private CaptchaUtil() {}
	
	public static void outputCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		int codeLength = 4;
		
		String randomString = getRandomString(codeLength);
		
		System.out.println(randomString.replace(" ", ""));
		
		request.getSession(true).setAttribute("randomString", randomString.replace(" ", ""));
		
		int width = 100;
		int height = 40;
		
		int fSize = 20;
		
		int strX = 15;
		int strY = 25;
		
		String imageEncode = "JPG";
		
		Color color = getRandomColor();
		Color reverse = getReverseColor(color);
		
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		
		Graphics2D g = bi.createGraphics();
		
		g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, fSize));
		
		g.setColor(color);
		
		g.fillRect(0, 0, width, height);
		
		g.setColor(reverse);
		
		g.drawString(randomString, strX, strY);
		
		for (int i = 0, n = random.nextInt(100); i < n; i++) {
			g.drawRect(random.nextInt(width), random.nextInt(height),1,1);
		}
		
		if(imageEncode.equals("JPG")) {
			response.setContentType("image/jpeg");
		}else if (imageEncode.equals("PNG")) {
			response.setContentType("image/png");
		}else if (imageEncode.equals("GIF")) {
			response.setContentType("image/gif");
		}else {
			imageEncode = "JPG";
			response.setContentType("image/jpeg");
		}
		
		OutputStream out = response.getOutputStream();
		
		ImageIO.write(bi, imageEncode, out);
		
		out.flush();
		
		
	}
	
	
	
	

	private static Color getRandomColor() {
		Random random = new Random();
        return new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
	}

	private static Color getReverseColor(Color color) {
		return new Color(255-color.getRed(), 255-color.getGreen(), 255-color.getBlue());
	}

	private static final char[] CHARS = {'2','3','4','5','6','7','8','9','A'};
	
	private static Random random = new Random();

	private static String getRandomString(int codeLength) {
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < codeLength; i++) {
			buffer.append(CHARS[random.nextInt(CHARS.length)]+" ");
		}
		return buffer.toString();
	}
	
	
	
	
	
	
	
	
}
